import React, { useState } from 'react'
import { Upload, Icon, Button, Radio, message, Alert } from 'antd'
import { importFile } from '../../request/order'

function Import() {
  const [file, setFile] = useState(null)
  const [isLoading, setIsLoading] = useState(false)
  const [importCount, setImportCount] = useState({})
  const [isShowAlert, setIsShowAlert] = useState(false)
  const onSubmit = async() => {
    if (!file) {
      message.error('请选择上传文件')
      return false
    }
    setIsShowAlert(false)
    const formData = new FormData()
    formData.append('file', file)
    setIsLoading(true)
    const res = await importFile(formData)
    setIsLoading(false)
    if (res.code) {
      message.error(res.message)
      return false
    }
    setIsShowAlert(true)
    setImportCount(res.data || {})
  }

  const beforeUpload = file => {
    setFile(file)
    return false
  }

  const handleChange = info => {
    if (info.fileList.length === 0) {
      setFile(null)
    }
  }

  return (
    <div className="order-import">
      <div>
        导入类型：
        <Radio.Group value={1}>
          <Radio value={1}>快递信息</Radio>
        </Radio.Group>
      </div>
      <div className="template">
        <a href="http://file.lfcxwifi.com/%E5%BF%AB%E9%80%92%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx" target="_blank">模板下载</a>
      </div>
      <div className="upload-wrapper">
        <Upload
          beforeUpload={beforeUpload}
          accept=".xls,.xlsx"
          onChange={handleChange}
        >
          <Button disabled={!!file}>
            <Icon type="upload"/>  点击上传
          </Button>
        </Upload>
      </div>
      {isShowAlert && (
        <div className="result">
          <Alert message={`成功${importCount.succ_count || 0}条，失败${importCount.fail_count || 0}条`} type="info"/>
        </div>
      )}
      <div className="button-wrapper">
        <Button type="primary" onClick={onSubmit} loading={isLoading}>导入</Button>
      </div>
    </div>
  )
}

export default Import
